﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace UmbSearch2.UserControls
{
	public partial class Pager : System.Web.UI.UserControl
	{
		public int CurrentPage { get; set; }
		public int TotalResults { get; set; }
		public int NumberOfSearchResultItemsPerPage { get; set; }

		protected void Page_Load(object sender, EventArgs e)
		{
			CreatePagingLinks();
		}

		private void CreatePagingLinks()
		{
			// calculate amount of pages
			int numberOfPages = (int)Math.Ceiling((double)TotalResults / NumberOfSearchResultItemsPerPage);

			for (int i = 1; i <= numberOfPages; i++)
			{
				HyperLink hl = new HyperLink();
				if (CurrentPage == i)
				{
					hl.Text = "<strong>" + i + "</strong> ";
				}
				else
				{
					hl.Text = i + " ";
				}

				if(i != numberOfPages)
				{
					hl.Text = hl.Text + "| ";
				}

				hl.NavigateUrl = CreateUrl(i);
				hl.Style.Add(HtmlTextWriterStyle.TextDecoration, "none");
				plhPaging.Controls.Add(hl);
			}

			if (CurrentPage == 1)
			{
				hplPrevious.Visible = false;
			}
			else
			{
				hplPrevious.Visible = true;
				hplPrevious.NavigateUrl = CreateUrl(CurrentPage - 1);
			}

			if (CurrentPage == numberOfPages)
			{
				hplNext.Visible = false;
			}
			else
			{
				hplNext.Visible = true;
				hplNext.NavigateUrl = CreateUrl(CurrentPage + 1);
			}
		}

		private string CreateUrl(int page)
		{
			string url;

			if (!string.IsNullOrEmpty(Request.QueryString["page"]))
			{
				int index = Request.RawUrl.IndexOf("&page=");
				url = Request.RawUrl.Remove(index);
			}
			else
			{
				url = Request.RawUrl;
			}

			string newQueryString = "&page=" + page;
			return string.Concat(url, newQueryString);
		}
	}
}